<template>
  <a-spin :spinning="confirmLoading">
    <ants-form-container :disabled="formDisabled">
      <a-form slot="detail" :form="form">
        <a-row>
          <a-col :span="12">
            <a-form-item label="用户姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['realname', validatorRules.realname]" placeholder="请输入姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户账号" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                v-decorator.trim="['username', validatorRules.username]"
                placeholder="请输入用户名"
                :read-only="!!model.id"
              />
            </a-form-item>
          </a-col>
          <template v-if="!model.id">
            <a-col :span="12">
              <a-form-item label="登陆密码" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input v-decorator="['password', validatorRules.password]" type="password" placeholder="请输入登陆密码" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="确认密码" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="['confirmPassword', validatorRules.confirmPassword]"
                  type="password"
                  placeholder="请确认密码"
                  @blur="handleConfirmBlur"
                />
              </a-form-item>
            </a-col>
          </template>
          <a-col :span="12">
            <a-form-item label="生日" :label-col="labelCol" :wrapper-col="wrapperCol">
              <ants-date v-decorator="['birthday']" placeholder="请选择生日" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" :label-col="labelCol" :wrapper-col="wrapperCol">
              <ants-dict-select-tag
                v-decorator="['sex']"
                type="list"
                :trigger-change="true"
                dict-code="sex"
                placeholder="请选择性别"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="邮箱" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['email', validatorRules.email]" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="电话" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input v-decorator="['phone', validatorRules.phone]" placeholder="请输入手机号码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="角色分配" :label-col="labelCol" :wrapper-col="wrapperCol">
              <!--              <ants-search-select-tag-->
              <!--                ref="searchSelectTag"-->
              <!--                style="width: 72%"-->
              <!--                v-model="selectedRole"-->
              <!--                dict="sys_role,role_name,id"-->
              <!--              />-->
              <a-select
                v-model="selectedRole"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择用户角色"
                option-filter-prop="children"
                :get-popup-container="(target) => target.parentNode"
              >
                <a-select-option v-for="(role,roleindex) in roleList" :key="roleindex.toString()" :value="role.id">
                  {{ role.roleName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="头像" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <ants-image-upload biz-path="ants-avatar" v-decorator="['avatar', validatorRules.avatar]" is-multiple />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ants-form-container>
  </a-spin>
</template>

<script>
import AntsFormContainer from '@/components/ants/AntsFormContainer'
import pick from 'lodash.pick'
import AntsImageUpload from '@/components/ants/AntsImageUpload'
import AntsDate from '@/components/ants/AntsDate'
import AntsDictSelectTag from '@/components/dict/AntsDictSelectTag'
import store from '@/store'
import { duplicateCheck, queryUserRole, queryRoleAll } from '@/api/api'

export default {
  name: 'UserForm',
  components: {
    AntsFormContainer,
    AntsImageUpload,
    AntsDictSelectTag,
    AntsDate
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      model: {},
      roleList: [],
      selectedRole: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      validatorRules: {
        username: {
          rules: [{
            required: true, message: '请输入用户账号!'
          }, {
            validator: this.validateUsername
          }]
        },
        avatar: {
          rules: [{
            required: true, message: '请上传头像!'
          }]
        },
        password: {
          rules: [{
            required: true,
            pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
            message: '密码最少8位字符，由 数字、大小写字母 和 特殊符号 组成!'
          }, {
            validator: this.validateToNextPassword
          }]
        },
        confirmPassword: {
          rules: [{
            required: true, message: '请重新输入登陆密码!'
          }, {
            validator: this.compareToFirstPassword
          }]
        },
        realname: { rules: [{ required: true, message: '请输入用户名称!' }] },
        phone: { rules: [{ validator: this.validatePhone }] },
        email: {
          rules: [{
            validator: this.validateEmail
          }]
        }
      },
      url: {
        add: '/sys/user/add',
        edit: '/sys/user/edit'
      },
      confirmLoading: false,
      confirmDirty: false,
      userId: ''
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    }
  },
  methods: {
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.initialRoleList()
      this.userId = record.id
      this.model = Object.assign({}, record)
      this.visible = true
      if (record.hasOwnProperty('id')) {
        this.loadUserRoles(record.id)
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'realname', 'username', 'birthday', 'sex', 'email', 'phone', 'avatar'))
      })
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form
      const confirmpassword = form.getFieldValue('confirmpassword')

      if (value && confirmpassword && value !== confirmpassword) {
        callback('两次输入的密码不一样！')
      }
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        // update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          // update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------

          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('手机号已存在!')
            }
          })
        } else {
          callback('请输入正确格式的手机号码!')
        }
      }
    },
    validateEmail(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'email',
            fieldVal: value,
            dataId: this.userId
          }
          duplicateCheck(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback('邮箱已存在!')
            }
          })
        } else {
          callback('请输入正确格式的邮箱!')
        }
      }
    },
    validateUsername(rule, value, callback) {
      var params = {
        tableName: 'sys_user',
        fieldName: 'username',
        fieldVal: value,
        dataId: this.userId
      }
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback('用户名已存在!')
        }
      })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          const formData = Object.assign(this.model, values)
          // update-end-author:taoyan date:2020710 for:多租户配置
          formData.selectedroles = this.selectedRole.length > 0 ? this.selectedRole.join(',') : ''
          // formData.selecteddeparts = this.userDepartModel.departIdList.length > 0 ? this.userDepartModel.departIdList.join(',') : ''

          // eslint-disable-next-line no-unused-vars
          var url = ''
          var method = ''
          if (!this.model.id) {
            url = that.url.add
            method = 'post'
          } else {
            url = that.url.edit
            method = 'put'
          }
          store.dispatch('user/addOrUpdateUser', {
            url: url,
            method: method,
            params: formData
          }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    initialRoleList() {
      queryRoleAll().then((res) => {
        if (res.success) {
          this.roleList = res.result
        }
      })
    },
    loadUserRoles(userid) {
      queryUserRole({ userid: userid }).then((res) => {
        if (res.success) {
          this.selectedRole = res.result
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
